package com.a.module_login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.RegexUtils;
import com.example.myframe.BaseNetApp;
import com.example.myframe.DistDeptApp;
import com.example.myframe.utils.HttpUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.a.lib_base.base.ui.BaseNetStateActivity;
import com.a.lib_bean.PermissionUtil;
import com.a.lib_bean.api.CheckPermissionApi;
import com.a.lib_bean.api.Url;
import com.a.lib_bean.enums.PermissionType;
import com.a.lib_network.bean.HttpData;
import com.a.lib_network.enums.NetStateEnum;
import com.a.lib_network.http.HttpDataCallBack;
import com.a.lib_network.http.RequestHandler;
import com.a.lib_route.home.HomeNav;
import com.a.lib_route.home.HomeRouter;
import com.a.lib_utils.DialogUtil;
import com.a.lib_utils.TipUtil;
import com.a.lib_utils.ToolsUtils;
import com.a.module_login.databinding.LoginActivityLoginBinding;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tencent.mmkv.MMKV;

import java.util.List;
import java.util.Objects;

/**
 * 添加东西前，请思考耦合度
 */
@Route(path = "/login/login")
public class LoginActivity extends BaseNetStateActivity<LoginActivityLoginBinding, LoginViewModel> {

    private static final String TAG = LoginActivity.class.getSimpleName();
    public static boolean isFirst = true;//如果是第一次打开就有进行版本判断
    private MMKV kv;
    private boolean isRelease;

    @Override
    public LoginActivityLoginBinding viewBinding(ViewGroup view) {
        return LoginActivityLoginBinding.inflate(getLayoutInflater());
    }

    // TODO: 2022/7/25 应用类型判断的命根,但过于耦合
    private PermissionType type;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*初始化*/
        type = PermissionType.valueOf(BaseNetApp.moduleName);
        isRelease = BuildConfig.isRelease;
        ARouter.getInstance().inject(this);
        Log.i(TAG, "onCreate: " + type);
        PermissionUtil.initType(type);
        kv = MMKV.defaultMMKV();
        initView();
        /**/
        openPermissions();
        netStateViewModel.getLiveData().observe(this, netState -> {
            if (netState.getState() == NetStateEnum.SUCCESS) {
                kv.encode("username", b.etUsername.getText().toString());
                checkPermissions(Objects.requireNonNull(DistDeptApp.getEmployee()).getEmployeeID());
            }
            simpleHandleState(netState);
        });
    }


    @Override
    public String setTitle() {
        return null;
    }

    @Override
    public int setBarBackground() {
        return 0;
    }


    @SuppressLint("SetTextI18n")
    private void initView() {
        b.loginTvLogoTitle.setText("a " + type + " APP");
        b.etUsername.setText(kv.decodeString("username", ""));//上次登录成功的用户名
        b.tvIp.setOnClickListener(v -> {
            QMUIDialog.EditTextDialogBuilder editTextDialog = DialogUtil.getEditTextDialog(this);
            String ip = kv.decodeString("ip", Url.host2);
            editTextDialog.setTitle("输入IP").setDefaultText(ip).setPlaceholder("请输入")
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", (dialog, index) -> {
                        String s = editTextDialog.getEditText().getText().toString();
                        if (RegexUtils.isIP(s)) {//RegexUtils black的第三方库工具类，强烈建议需要什么功能先去查一遍是否已经支持
                            BaseNetApp.setNetConfig("http://" + s + ":8181", 6
                                    , new RequestHandler(this.getApplication()));//更改ip后重新初始化
                            Url.host = "http://" + s + ":8181";
                            kv.encode("ip", s);
                            TipUtil.toast("保存成功");
                            dialog.dismiss();
                        } else TipUtil.toast("请输入正确的格式");
                    }).show();
        });
        b.btnLogin.setOnClickListener(v -> {
            String username = b.etUsername.getText().toString();
            //MD5加密
            String password = ToolsUtils.md5(b.etPassword.getText().toString());
            if (username.equals("") || password.equals("")) {
                TipUtil.failTip(LoginActivity.this, "请输入账号密码");
                return;   //這裏是可以自己輸入
            }
            netStateViewModel.get(type, b.etUsername.getText().toString(), b.etPassword.getText().toString());
        });
    }

    /**
     * 申请权限
     * 当项目的 targetSdkVersion >= 30 时，则不能申请 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE 权限，
     * 而是应该申请 MANAGE_EXTERNAL_STORAGE 权限
     */
    private void openPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
//                .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .permission(Permission.CAMERA)
//                .permission("android.permission.FOREGROUND_SERVICE")
        // 申请多个权限
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            if (isRelease && isFirst)
                                HttpUtils.showUpdateDialog(LoginActivity.this, Url.doCheckUpdate(type), BaseNetApp.APP_VERSION, b.view5);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            TipUtil.toast("拒绝会导致功能无法正常使用");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(LoginActivity.this, permissions);
                        } else {
                            TipUtil.toast("拒绝会导致功能无法正常使用");
                        }
                    }
                });
    }

//

    /**
     * 用户拥有的软件权限
     * 当权限为负数表示不用判断，后台直接返回
     */
    private void checkPermissions(int id) {
        new HttpDataCallBack<HttpData<CheckPermissionApi>, CheckPermissionApi>(this) {
        }.get(new CheckPermissionApi(type, id, PermissionUtil.getAllPermissionCode()), checkPermissionApi -> {
            PermissionUtil.clear();//重新登录需要清除原有保存权限
            PermissionUtil.addAll(checkPermissionApi.getPermissionIDs());
            TipUtil.dismiss();
            HomeNav.INSTANCE.buildMain().withString("selectItemPath", HomeRouter.selectItemPath(type)).navigation();
            finish();
        });
    }


    public static void actionStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        isFirst = false;
        context.startActivity(intent);
    }


}
